﻿using System;
using System.Linq;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Transactions;
using System.Data.Entity.Validation;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Reflection;

namespace OpenWeb.Dal.Models
{
    
    
    public  class ApplicationDbEntities : DbContext
    {

      static ApplicationDbEntities()
      {
        //Database.SetInitializer<GoldCrmDbEntities>(
        // new System.Data.Entity.DropCreateDatabaseIfModelChanges<GoldCrmDbEntities>()); 
      }

      public ApplicationDbEntities()
            : base("name="+   GlobalInfo.ConnStringName )
        {

          Configuration.ProxyCreationEnabled = false; //assicura classi e non proxy
          //Configuration.LazyLoadingEnabled 
          //Configuration.AutoDetectChangesEnabled 
          Configuration.ValidateOnSaveEnabled = true;
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
          // Modify The Code First conventions to not use PluralizingTableName
          modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
          SetFluentApi(modelBuilder);         

          base.OnModelCreating(modelBuilder);

        }

        private void SetFluentApi(DbModelBuilder modelBuilder)
        {
           // modelBuilder.Entity<Contact>().HasOptional(xx => xx.Profile).WithRequired();
        }
              

        public DbSet<Contact> Contacts { get; set; }
        public DbSet<Address> Adresses { get; set; }
                
        public DbSet<Document> Document { get; set; }
        public DbSet<Reminder> Reminder { get; set; }
        public DbSet<UserProfile> UserProfiles { get; set; }


        public DbSet<ContactProfile> ContactProspect { get; set; }

        public DbSet<Message> Messagges { get; set; }



      //*********

        #region azioni

        public int SaveEntityTransactional()
        {
          int tot = 0;

          using (TransactionScope transaction = new TransactionScope(TransactionScopeOption.Required))
          {
            ((IObjectContextAdapter)this).ObjectContext.Connection.Open();
            tot = this.SaveChanges();
            transaction.Complete();

            return tot;
          }
        }//fM


        protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
        {
          List<DbValidationError> validationErrors = new List<DbValidationError>();

          // Check for duplicate location names

          //if (entityEntry.Entity is Location)
          //{
          //  Location location = entityEntry.Entity as Location;

          //  // Select the existing location

          //  var existingLocation = (from l in Locations
          //                          where l.Name == location.Name && l.LocationId != location.LocationId
          //                          select l).FirstOrDefault();

          //  // If there is an existing location, throw an error

          //  if (existingLocation != null)
          //  {
          //    validationErrors.Add(new DbValidationError("Name", "There is already a location with the name '" + location.Name + "'"));
          //    return new DbEntityValidationResult(entityEntry, validationErrors);
          //  }
          //}

          return base.ValidateEntity(entityEntry, items);
        }


        private string GetProductVersion()
        {
          return typeof(DbContext).Assembly.GetCustomAttributes(false)
               .OfType<AssemblyInformationalVersionAttribute>()
               .Single().InformationalVersion;
        }

        #endregion


        #region creation

        //protected override void OnModelCreating(DbModelBuilder modelBuilder)
        //{
        //  // Modify The Code First conventions to not use PluralizingTableName
        //  modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        //}

        #endregion




    }//




  

}
